package com.haredot.controller;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.MathGenerator;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource(name="redisJdkTemplate")
    private RedisTemplate<String, AbstractCaptcha> redisTemplate ;

    /**
     * 生成验证码
     * @return
     */
    @GetMapping("/code")
    public HttpEntity<byte[]> generatorCode(@RequestParam(value = "w", required = false, defaultValue = "140") Integer width,
                                            @RequestParam(value = "h", required = false, defaultValue = "40") Integer height,
                                            @RequestParam("u") String base64Tel) {

        AbstractCaptcha captcha = CaptchaUtil.createLineCaptcha(width, height, 4, 10);
        // 添加四则运算
        if (Math.random() < 0.5) captcha.setGenerator(new MathGenerator());
        // 生成 验证码
        captcha.createCode();

        String suffix = new String(Base64.getDecoder().decode(base64Tel),StandardCharsets.UTF_8);
        // 将验证码 写入到 Redis 中, 且有效时间 1 分钟
        redisTemplate.opsForValue().set("captcha::code::" + suffix, captcha, Duration.ofMinutes(1));
        // 生成 对应的图片
        byte[] imageBytes = captcha.getImageBytes();

        return ResponseEntity.ok()
                .header("Content-Type", "image/gif")
                .body(imageBytes);
    }
}
